home *** CD-ROM | disk | FTP | other *** search
/ Graphics Plus / Graphics Plus.iso / general / gems / g_gemsi.lha / GraphicsGems / NearestPoint.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-04-10  |  12.1 KB  |  485 lines

  1. /*
  2. Solving the Nearest Point-on-Curve Problem 
  3. and
  4. A Bezier Curve-Based Root-Finder
  5. by Philip J. Schneider
  6. from "Graphics Gems", Academic Press, 1990
  7. */
  8.  
  9.  /*    point_on_curve.c    */        
  10.                                     
  11. #include <stdio.h>
  12. #include <malloc.h>
  13. #include <math.h>
  14. #include "GraphicsGems.h"
  15.  
  16. #define TESTMODE
  17.  
  18. /*
  19.  *  Forward declarations
  20.  */
  21.         Point2  NearestPointOnCurve();
  22. static    int    FindRoots();
  23. static    Point2    *ConvertToBezierForm();
  24. static    double    ComputeXIntercept();
  25. static    int    ControlPolygonFlatEnough();
  26. static    int    CrossingCount();
  27. static    Point2    Bezier();
  28. static    Vector2    *V2Sub();
  29. static    Vector2    V2ScaleII();
  30.  
  31.         int        MAXDEPTH = 64;    /*  Maximum depth for recursion */
  32. #define    EPSILON    (ldexp(1.0,-MAXDEPTH-1)) /*Flatness control value */
  33. #define    DEGREE    3            /*  Cubic Bezier curve        */
  34. #define    W_DEGREE 5            /*  Degree of eqn to find roots of */
  35.  
  36. #ifdef TESTMODE
  37. /*
  38.  *  main :
  39.  *    Given a cubic Bezier curve (i.e., its control points), and some
  40.  *    arbitrary point in the plane, find the point on the curve
  41.  *    closest to that arbitrary point.
  42.  */
  43. main()
  44. {
  45.    
  46.  static Point2 bezCurve[4] = {    /*  A cubic Bezier curve    */
  47.     { 0.0, 0.0 },
  48.     { 1.0, 2.0 },
  49.     { 3.0, 3.0 },
  50.     { 4.0, 2.0 },
  51.     };
  52.     static Point2 arbPoint = { 3.5, 2.0 }; /*Some arbitrary point*/
  53.     Point2    pointOnCurve;         /*  Nearest point on the curve */
  54.  
  55.     /*  Find the closest point */
  56.     pointOnCurve = NearestPointOnCurve(arbPoint, bezCurve);
  57.     printf("pointOnCurve : (%4.4f, %4.4f)\n", pointOnCurve.x,             pointOnCurve.y);
  58. }
  59. #endif /* TESTMODE */
  60.  
  61.  
  62. /*
  63.  *  NearestPointOnCurve :
  64.  *      Compute the parameter value of the point on a Bezier
  65.  *        curve segment closest to some arbtitrary, user-input point.
  66.  *        Return the point on the curve at that parameter value.
  67.  *
  68.  */
  69. Point2 NearestPointOnCurve(P, V)
  70.     Point2     P;            /* The user-supplied point      */
  71.     Point2     *V;            /* Control points of cubic Bezier */
  72. {
  73.     Point2    *w;            /* Ctl pts for 5th-degree eqn    */
  74.     double     t_candidate[W_DEGREE];    /* Possible roots        */     
  75.     int     n_solutions;        /* Number of roots found    */
  76.     double    t;            /* Parameter value of closest pt*/
  77.  
  78.     /*  Convert problem to 5th-degree Bezier form    */
  79.     w = ConvertToBezierForm(P, V);
  80.  
  81.     /* Find all possible roots of 5th-degree equation */
  82.     n_solutions = FindRoots(w, W_DEGREE, t_candidate, 0);
  83.     free((char *)w);
  84.  
  85.     /* Compare distances of P to all candidates, and to t=0, and t=1 */
  86.     {
  87.         double     dist, new_dist;
  88.         Point2     p;
  89.         Vector2  v;
  90.         int        i;
  91.  
  92.     
  93.     /* Check distance to beginning of curve, where t = 0    */
  94.         dist = V2SquaredLength(V2Sub(&P, &V[0], &v));
  95.             t = 0.0;
  96.  
  97.     /* Find distances for candidate points    */
  98.         for (i = 0; i < n_solutions; i++) {
  99.             p = Bezier(V, DEGREE, t_candidate[i], NULL, NULL);
  100.             new_dist = V2SquaredLength(V2Sub(&P, &p, &v));
  101.             if (new_dist < dist) {
  102.                     dist = new_dist;
  103.                     t = t_candidate[i];
  104.             }
  105.         }
  106.  
  107.     /* Finally, look at distance to end point, where t = 1.0 */
  108.         new_dist = V2SquaredLength(V2Sub(&P, &V[DEGREE], &v));
  109.             if (new_dist < dist) {
  110.                 dist = new_dist;
  111.             t = 1.0;
  112.         }
  113.     }
  114.  
  115.     /*  Return the point on the curve at parameter value t */
  116.     printf("t : %4.12f\n", t);
  117.     return (Bezier(V, DEGREE, t, NULL, NULL));
  118. }
  119.  
  120.  
  121. /*
  122.  *  ConvertToBezierForm :
  123.  *        Given a point and a Bezier curve, generate a 5th-degree
  124.  *        Bezier-format equation whose solution finds the point on the
  125.  *      curve nearest the user-defined point.
  126.  */
  127. static Point2 *ConvertToBezierForm(P, V)
  128.     Point2     P;            /* The point to find t for    */
  129.     Point2     *V;            /* The control points        */
  130. {
  131.     int     i, j, k, m, n, ub, lb;    
  132.     double     t;            /* Value of t for point P    */
  133.     int     row, column;        /* Table indices        */
  134.     Vector2     c[DEGREE+1];        /* V(i)'s - P            */
  135.     Vector2     d[DEGREE];        /* V(i+1) - V(i)        */
  136.     Point2     *w;            /* Ctl pts of 5th-degree curve  */
  137.     double     cdTable[3][4];        /* Dot product of c, d        */
  138.     static double z[3][4] = {    /* Precomputed "z" for cubics    */
  139.     {1.0, 0.6, 0.3, 0.1},
  140.     {0.4, 0.6, 0.6, 0.4},
  141.     {0.1, 0.3, 0.6, 1.0},
  142.     };
  143.  
  144.  
  145.     /*Determine the c's -- these are vectors created by subtracting*/
  146.     /* point P from each of the control points                */
  147.     for (i = 0; i <= DEGREE; i++) {
  148.         V2Sub(&V[i], &P, &c[i]);
  149.     }
  150.     /* Determine the d's -- these are vectors created by subtracting*/
  151.     /* each control point from the next                    */
  152.     for (i = 0; i <= DEGREE - 1; i++) { 
  153.         d[i] = V2ScaleII(V2Sub(&V[i+1], &V[i], &d[i]), 3.0);
  154.     }
  155.  
  156.     /* Create the c,d table -- this is a table of dot products of the */
  157.     /* c's and d's                            */
  158.     for (row = 0; row <= DEGREE - 1; row++) {
  159.         for (column = 0; column <= DEGREE; column++) {
  160.             cdTable[row][column] = V2Dot(&d[row], &c[column]);
  161.         }
  162.     }
  163.  
  164.     /* Now, apply the z's to the dot products, on the skew diagonal*/
  165.     /* Also, set up the x-values, making these "points"        */
  166.     w = (Point2 *)malloc((unsigned)(W_DEGREE+1) * sizeof(Point2));
  167.     for (i = 0; i <= W_DEGREE; i++) {
  168.         w[i].y = 0.0;
  169.         w[i].x = (double)(i) / W_DEGREE;
  170.     }
  171.  
  172.     n = DEGREE;
  173.     m = DEGREE-1;
  174.     for (k = 0; k <= n + m; k++) {
  175.         lb = MAX(0, k - m);
  176.         ub = MIN(k, n);
  177.         for (i = lb; i <= ub; i++) {
  178.             j = k - i;
  179.             w[i+j].y += cdTable[j][i] * z[j][i];
  180.         }
  181.     }
  182.  
  183.     return (w);
  184. }
  185.  
  186.  
  187. /*
  188.  *  FindRoots :
  189.  *    Given a 5th-degree equation in Bernstein-Bezier form, find
  190.  *    all of the roots in the interval [0, 1].  Return the number
  191.  *    of roots found.
  192.  */
  193. static int FindRoots(w, degree, t, depth)
  194.     Point2     *w;            /* The control points        */
  195.     int     degree;        /* The degree of the polynomial    */
  196.     double     *t;            /* RETURN candidate t-values    */
  197.     int     depth;        /* The depth of the recursion    */
  198. {  
  199.     int     i;
  200.     Point2     Left[W_DEGREE+1],    /* New left and right         */
  201.               Right[W_DEGREE+1];    /* control polygons        */
  202.     int     left_count,        /* Solution count from        */
  203.             right_count;        /* children            */
  204.     double     left_t[W_DEGREE+1],    /* Solutions from kids        */
  205.                right_t[W_DEGREE+1];
  206.  
  207.     switch (CrossingCount(w, degree)) {
  208.            case 0 : {    /* No solutions here    */
  209.          return 0;    
  210.          break;
  211.     }
  212.     case 1 : {    /* Unique solution    */
  213.         /* Stop recursion when the tree is deep enough    */
  214.         /* if deep enough, return 1 solution at midpoint     */
  215.         if (depth >= MAXDEPTH) {
  216.             t[0] = (w[0].x + w[W_DEGREE].x) / 2.0;
  217.             return 1;
  218.         }
  219.         if (ControlPolygonFlatEnough(w, degree)) {
  220.             t[0] = ComputeXIntercept(w, degree);
  221.             return 1;
  222.         }
  223.         break;
  224.     }
  225. }
  226.  
  227.     /* Otherwise, solve recursively after    */
  228.     /* subdividing control polygon        */
  229.     Bezier(w, degree, 0.5, Left, Right);
  230.     left_count  = FindRoots(Left,  degree, left_t, depth+1);
  231.     right_count = FindRoots(Right, degree, right_t, depth+1);
  232.  
  233.  
  234.     /* Gather solutions together    */
  235.     for (i = 0; i < left_count; i++) {
  236.         t[i] = left_t[i];
  237.     }
  238.     for (i = 0; i < right_count; i++) {
  239.          t[i+left_count] = right_t[i];
  240.     }
  241.  
  242.     /* Send back total number of solutions    */
  243.     return (left_count+right_count);
  244. }
  245.  
  246.  
  247. /*
  248.  * CrossingCount :
  249.  *    Count the number of times a Bezier control polygon 
  250.  *    crosses the 0-axis. This number is >= the number of roots.
  251.  *
  252.  */
  253. static int CrossingCount(V, degree)
  254.     Point2    *V;            /*  Control pts of Bezier curve    */
  255.     int        degree;            /*  Degreee of Bezier curve     */
  256. {
  257.     int     i;    
  258.     int     n_crossings = 0;    /*  Number of zero-crossings    */
  259.     int        sign, old_sign;        /*  Sign of coefficients    */
  260.  
  261.     sign = old_sign = SGN(V[0].y);
  262.     for (i = 1; i <= degree; i++) {
  263.         sign = SGN(V[i].y);
  264.         if (sign != old_sign) n_crossings++;
  265.         old_sign = sign;
  266.     }
  267.     return n_crossings;
  268. }
  269.  
  270.  
  271.  
  272. /*
  273.  *  ControlPolygonFlatEnough :
  274.  *    Check if the control polygon of a Bezier curve is flat enough
  275.  *    for recursive subdivision to bottom out.
  276.  *
  277.  */
  278. static int ControlPolygonFlatEnough(V, degree)
  279.     Point2    *V;        /* Control points    */
  280.     int     degree;        /* Degree of polynomial    */
  281. {
  282.     int     i;            /* Index variable        */
  283.     double     *distance;        /* Distances from pts to line    */
  284.     double     max_distance_above;    /* maximum of these        */
  285.     double     max_distance_below;
  286.     double     error;            /* Precision of root        */
  287.     Vector2     t;            /* Vector from V[0] to V[degree]*/
  288.     double     intercept_1,
  289.                intercept_2,
  290.                left_intercept,
  291.                right_intercept;
  292.     double     a, b, c;        /* Coefficients of implicit    */
  293.                         /* eqn for line from V[0]-V[deg]*/
  294.  
  295.     /* Find the  perpendicular distance        */
  296.     /* from each interior control point to     */
  297.     /* line connecting V[0] and V[degree]    */
  298.     distance = (double *)malloc((unsigned)(degree + 1) *                     sizeof(double));
  299.     {
  300.     double    abSquared;
  301.  
  302.     /* Derive the implicit equation for line connecting first *'
  303.     /*  and last control points */
  304.     a = V[0].y - V[degree].y;
  305.     b = V[degree].x - V[0].x;
  306.     c = V[0].x * V[degree].y - V[degree].x * V[0].y;
  307.  
  308.     abSquared = (a * a) + (b * b);
  309.  
  310.         for (i = 1; i < degree; i++) {
  311.         /* Compute distance from each of the points to that line    */
  312.             distance[i] = a * V[i].x + b * V[i].y + c;
  313.             if (distance[i] > 0.0) {
  314.                 distance[i] = (distance[i] * distance[i]) / abSquared;
  315.             }
  316.             if (distance[i] < 0.0) {
  317.                 distance[i] = -((distance[i] * distance[i]) /                         abSquared);
  318.             }
  319.         }
  320.     }
  321.  
  322.  
  323.     /* Find the largest distance    */
  324.     max_distance_above = 0.0;
  325.     max_distance_below = 0.0;
  326.     for (i = 1; i < degree; i++) {
  327.         if (distance[i] < 0.0) {
  328.             max_distance_below = MIN(max_distance_below, distance[i]);
  329.         };
  330.         if (distance[i] > 0.0) {
  331.             max_distance_above = MAX(max_distance_above, distance[i]);
  332.         }
  333.     }
  334.     free((char *)distance);
  335.  
  336.     {
  337.     double    det, dInv;
  338.     double    a1, b1, c1, a2, b2, c2;
  339.  
  340.     /*  Implicit equation for zero line */
  341.     a1 = 0.0;
  342.     b1 = 1.0;
  343.     c1 = 0.0;
  344.  
  345.     /*  Implicit equation for "above" line */
  346.     a2 = a;
  347.     b2 = b;
  348.     c2 = c + max_distance_above;
  349.  
  350.     det = a1 * b2 - a2 * b1;
  351.     dInv = 1.0/det;
  352.     
  353.     intercept_1 = (b1 * c2 - b2 * c1) * dInv;
  354.  
  355.     /*  Implicit equation for "below" line */
  356.     a2 = a;
  357.     b2 = b;
  358.     c2 = c + max_distance_below;
  359.     
  360.     det = a1 * b2 - a2 * b1;
  361.     dInv = 1.0/det;
  362.     
  363.     intercept_2 = (b1 * c2 - b2 * c1) * dInv;
  364.     }
  365.  
  366.     /* Compute intercepts of bounding box    */
  367.     left_intercept = MIN(intercept_1, intercept_2);
  368.     right_intercept = MAX(intercept_1, intercept_2);
  369.  
  370.     error = 0.5 * (right_intercept-left_intercept);    
  371.     if (error < EPSILON) {
  372.         return 1;
  373.     }
  374.     else {
  375.         return 0;
  376.     }
  377. }
  378.  
  379.  
  380.  
  381. /*
  382.  *  ComputeXIntercept :
  383.  *    Compute intersection of chord from first control point to last
  384.  *      with 0-axis.
  385.  * 
  386.  */
  387. static double ComputeXIntercept(V, degree)
  388.     Point2     *V;            /*  Control points    */
  389.     int        degree;         /*  Degree of curve    */
  390. {
  391.     double    XLK, YLK, XNM, YNM, XMK, YMK;
  392.     double    det, detInv;
  393.     double    S, T;
  394.     double    X, Y;
  395.  
  396.     XLK = 1.0 - 0.0;
  397.     YLK = 0.0 - 0.0;
  398.     XNM = V[degree].x - V[0].x;
  399.     YNM = V[degree].y - V[0].y;
  400.     XMK = V[0].x - 0.0;
  401.     YMK = V[0].y - 0.0;
  402.  
  403.     det = XNM*YLK - YNM*XLK;
  404.     detInv = 1.0/det;
  405.  
  406.     S = (XNM*YMK - YNM*XMK) * detInv;
  407.     T = (XLK*YMK - YLK*XMK) * detInv;
  408.     
  409.     X = 0.0 + XLK * S;
  410.     Y = 0.0 + YLK * S;
  411.  
  412.     return X;
  413. }
  414.  
  415.  
  416. /*
  417.  *  Bezier : 
  418.  *    Evaluate a Bezier curve at a particular parameter value
  419.  *      Fill in control points for resulting sub-curves if "Left" and
  420.  *    "Right" are non-null.
  421.  * 
  422.  */
  423. static Point2 Bezier(V, degree, t, Left, Right)
  424.     int     degree;        /* Degree of bezier curve    */
  425.     Point2     *V;            /* Control pts            */
  426.     double     t;            /* Parameter value        */
  427.     Point2     *Left;        /* RETURN left half ctl pts    */
  428.     Point2     *Right;        /* RETURN right half ctl pts    */
  429. {
  430.     int     i, j;        /* Index variables    */
  431.     Point2     Vtemp[W_DEGREE+1][W_DEGREE+1];
  432.  
  433.  
  434.     /* Copy control points    */
  435.     for (j =0; j <= degree; j++) {
  436.         Vtemp[0][j] = V[j];
  437.     }
  438.  
  439.     /* Triangle computation    */
  440.     for (i = 1; i <= degree; i++) {    
  441.         for (j =0 ; j <= degree - i; j++) {
  442.             Vtemp[i][j].x =
  443.                   (1.0 - t) * Vtemp[i-1][j].x + t * Vtemp[i-1][j+1].x;
  444.             Vtemp[i][j].y =
  445.                   (1.0 - t) * Vtemp[i-1][j].y + t * Vtemp[i-1][j+1].y;
  446.         }
  447.     }
  448.     
  449.     if (Left != NULL) {
  450.         for (j = 0; j <= degree; j++) {
  451.             Left[j]  = Vtemp[j][0];
  452.         }
  453.     }
  454.     if (Right != NULL) {
  455.         for (j = 0; j <= degree; j++) {
  456.             Right[j] = Vtemp[degree-j][j];
  457.         }
  458.     }
  459.  
  460.     return (Vtemp[degree][0]);
  461. }
  462.  
  463.  
  464. static Vector2 *V2Sub(a, b, c)
  465.     Vector2    *a, *b, *c;
  466. {
  467.     c->x = a->x - b->x;
  468.     c->y = a->y - b->y;
  469.  
  470.     return (c);
  471. }
  472.  
  473.  
  474. static Vector2 V2ScaleII(v, s)
  475.     Vector2    *v;
  476.     double    s;
  477. {
  478.     Vector2 result;
  479.  
  480.     result.x = v->x * s; result.y = v->y * s;
  481.     return (result);
  482. }
  483.  
  484.  
  485.